package com.mxpio.erp.equipment.controller;

import com.mxpio.erp.common.equipment.entity.EquipmentUpkeepTask;
import com.mxpio.erp.common.equipment.entity.EquipmentUpkeepTaskDetail;
import com.mxpio.erp.common.equipment.entity.EquipmentUpkeepTaskOperation;
import com.mxpio.erp.common.equipment.entity.EquipmentUpkeepTaskTransfer;
import com.mxpio.erp.common.equipment.service.EquipmentUpkeepTaskService;
import com.mxpioframework.common.exception.MBootException;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;


@Tag(name = "EquipmentUpkeepTaskController}", description = "保养任务")
@RestController
@RequestMapping("/erp/equipment/upkeep/task/")
public class EquipmentUpkeepTaskController {

    @Autowired
    private EquipmentUpkeepTaskService equipmentUpkeepTaskService;


    @GetMapping("list")
    @Operation(summary = "保养任务列表", description = "获取保养任务列表（无分页）", method = "GET")
    public Result<List<EquipmentUpkeepTask>> list(@Parameter(description = "查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<EquipmentUpkeepTask> list = equipmentUpkeepTaskService.list(EquipmentUpkeepTask.class, criteria);
        return Result.OK(list);
    }

    @GetMapping("page")
    @Operation(summary = "保养任务列表", description = "获取保养任务列表（分页）", method = "GET")
    public Result<Page<EquipmentUpkeepTask>> page(@Parameter(description = "查询参数") Criteria criteria, @RequestParam(name = "flag", defaultValue = "task") String flag, @Parameter(description = "每页条数") Integer pageSize, @Parameter(description = "页号") Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo - 1, pageSize);
        Page<EquipmentUpkeepTask> pageResult = equipmentUpkeepTaskService.listPage(EquipmentUpkeepTask.class, page, criteria);
        return Result.OK(pageResult);
    }

    @GetMapping("queryExecutingList")
    @Operation(summary = "保养任务列表-保养中列表查询", description = "获取保养任务列表-保养中列表查询", method = "GET")
    public Result<List<EquipmentUpkeepTask>> list() {
        List<EquipmentUpkeepTask> list = equipmentUpkeepTaskService.queryExecutingList();
        return Result.OK(list);
    }

    @GetMapping("list/{id}")
    @Operation(summary = "根据ID获取保养任务列表", description = "根据ID获取保养任务列表", method = "GET")
    public Result<EquipmentUpkeepTask> getById(@PathVariable(name = "id", required = true) String id) {
        EquipmentUpkeepTask equipmentUpkeepTask = equipmentUpkeepTaskService.getById(EquipmentUpkeepTask.class, id);
        return Result.OK(equipmentUpkeepTask);
    }

    @RequestMapping("add")
    @Operation(summary = "保存保养任务", description = "保存保养任务")
    public Result<EquipmentUpkeepTask> add(@RequestBody EquipmentUpkeepTask equipmentUpkeepTask) {
        try {
            equipmentUpkeepTaskService.saveTask(equipmentUpkeepTask);
        } catch (MBootException e) {
            return Result.error(e.getMessage());
        }
        return Result.OK(equipmentUpkeepTask);
    }

    @PutMapping("edit")
    @Operation(summary = "编辑保养任务", description = "编辑保养任务", method = "PUT")
    public Result<EquipmentUpkeepTask> edit(@RequestBody EquipmentUpkeepTask equipmentUpkeepTask) {
        try {
            equipmentUpkeepTaskService.updateTask(equipmentUpkeepTask);
        } catch (MBootException e) {
            return Result.error(e.getMessage());
        }
        return Result.OK(equipmentUpkeepTask);
    }

    @RequestMapping("release/{id}")
    @Operation(summary = "保存保养任务-下达", description = "保存保养任务-下达")
    public Result<?> release(@PathVariable(name = "id", required = true) String id) {
        equipmentUpkeepTaskService.release(id);
        return Result.OK("下达成功！");
    }

    @RequestMapping("dispatch/{id}/{executor}")
    @Operation(summary = "保存保养任务-派工", description = "保存保养任务-派工")
    public Result<?> dispatch(@PathVariable(name = "id", required = true) String id, @PathVariable(name = "executor", required = true) String executor) {
        equipmentUpkeepTaskService.dispatch(id, executor);
        return Result.OK("派工成功！");
    }

    @RequestMapping("grab/{id}")
    @Operation(summary = "保存保养任务-领单", description = "保存保养任务-领单")
    public Result<?> grab(@PathVariable(name = "id", required = true) String id) {
        equipmentUpkeepTaskService.grab(id);
        return Result.OK("领单成功！");
    }

    @RequestMapping("reSend/{id}/{executor}/{reason}")
    @Operation(summary = "保存保养任务-转单", description = "保存保养任务-转单")
    public Result<?> reSend(@PathVariable(name = "id", required = true) String id,
                            @PathVariable(name = "executor", required = true) String executor,
                            @PathVariable(name = "reason", required = true) String reason) {
        equipmentUpkeepTaskService.reSend(id, executor, reason);
        return Result.OK("转单成功！");
    }

    @RequestMapping("startExcut/{id}")
    @Operation(summary = "保存保养任务-开始执行", description = "保存保养任务-开始执行")
    public Result<?> startExcut(@PathVariable(name = "id", required = true) String id) {
        equipmentUpkeepTaskService.startExcut(id);
        return Result.OK("领单成功！");
    }

    @RequestMapping("excut")
    @Operation(summary = "保存保养任务-执行", description = "保存保养任务-执行")
    public Result<?> excut(@RequestBody EquipmentUpkeepTask upkeepTask) {
        equipmentUpkeepTaskService.excut(upkeepTask);
        return Result.OK("执行成功！");
    }

    @RequestMapping("stop")
    @Operation(summary = "保存保养任务-暂停", description = "保存保养任务-暂停")
    public Result<?> stop(@RequestBody EquipmentUpkeepTask upkeepTask) {
        equipmentUpkeepTaskService.stopUpkeepById(upkeepTask.getReason(), upkeepTask.getId());
        return Result.OK("暂停成功！");
    }

    @RequestMapping("end/{id}")
    @Operation(summary = "保存保养任务-暂停结束", description = "保存保养任务-暂停结束")
    public Result<?> endStop(@PathVariable(name = "id", required = true) String id) {
        equipmentUpkeepTaskService.endStop(id);
        return Result.OK("暂停结束成功！");
    }

    @DeleteMapping("remove/{ids}")
    @Operation(summary = "根据id删除保养任务", description = "删除保养任务,多个id用英文逗号分隔", method = "DELETE")
    public Result<EquipmentUpkeepTask> remove(@PathVariable(name = "ids", required = true) String ids) {
        String[] id = ids.split(",");
        for (String key : id) {
            equipmentUpkeepTaskService.delete(EquipmentUpkeepTask.class, key, new SmartCrudPolicyAdapter() {
                @Override
                public boolean beforeDelete(CrudContext context) {
                    Object o = context.getEntity();
                    if (o instanceof EquipmentUpkeepTask) {
                        try {
                            JpaUtil.lind(EquipmentUpkeepTaskDetail.class).equal("taskId", ((EquipmentUpkeepTask) o).getId()).delete();
                            JpaUtil.lind(EquipmentUpkeepTaskOperation.class).equal("taskId", ((EquipmentUpkeepTask) o).getId()).delete();
                            JpaUtil.lind(EquipmentUpkeepTaskTransfer.class).equal("taskId", ((EquipmentUpkeepTask) o).getId()).delete();
                        } catch (Exception e) {
                            return false;
                        }
                    }
                    return true;
                }
            });
        }
        return Result.OK();
    }


}
